package com.contain.bootelasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.contain.bootelasticsearch.config.ElasticSearchClientConfiguration;
import com.contain.bootelasticsearch.data.DataUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2021/3/4 19:38
 * @Description:
 */
@Service
public class JDGoodsService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private DataUtils dataUtils;

    public Boolean parseJDGoods(String keyword){
        List<Object> list = dataUtils.parseSearch(keyword);
        BulkRequest bulkRequest = new BulkRequest();
        for (Object o : list) {
            IndexRequest indexRequest = new IndexRequest("goods");
            indexRequest.source(JSON.toJSONString(o), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = null;
        try {
            bulk = client.bulk(bulkRequest, ElasticSearchClientConfiguration.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        boolean b = bulk.hasFailures();
        return !b;
    }

}
